package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.widget.ImageView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.ChatMessage;
import com.sywb.chuangyebao.bean.ChatSession;
import com.sywb.chuangyebao.bean.NewsOwner;
import com.sywb.chuangyebao.bean.UserInfo;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;

import org.bining.footstone.adapter.BaseRecyclerMultiItemAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.db.DbManager;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.TimeUtils;

import java.util.List;

public interface UserChatContract {

    interface View extends BaseRefreshContract.View {
        NewsOwner getChatOwner();
    }

    class Presenter extends BaseRefreshContract.Presenter<View> {

        private ChatAdapter recyclerAdapter;

        private NewsOwner newsOwner;

        private UserInfo userInfo;

        private int pageNumber = 1;

        @Override
        public void onStart() {
            super.onStart();
            newsOwner = mView.getChatOwner();

            String uid = SharedUtils.getString(Constants.USEROPENID);
            userInfo = DbManager.getInstance().queryById(uid, UserInfo.class);

            recyclerAdapter = new ChatAdapter(mActivity, mView);
            setRecyclerAdapter(recyclerAdapter, false);

            initData();
        }

        @Override
        public void initData() {
            onStartAsync();
            pageNumber = 1;
            getChatMessage();
        }

        @Override
        public void onStartRefresh() {
            pageNumber = 1;
            getChatMessage();
        }

        @Override
        public void onStartLoadMore() {
            pageNumber++;
            getChatMessage();
        }

        @Override
        public void onRecyclerItemChildClick(android.view.View view, int postion) {
            if (view.getId() == R.id.chat_state) {
                ChatMessage chatMessage = recyclerAdapter.getItem(postion);
                chatMessage.status = 3;
                recyclerAdapter.notifyDataSetChanged();
                chatSend(postion, chatMessage.msg);
            }
        }

        private void getChatMessage() {
            if (newsOwner == null) {
                return;
            }
            HttpUtils.chatMessage(newsOwner.uid, new HttpCallback<List<ChatMessage>>() {
                @Override
                public void onSuccess(List<ChatMessage> chatMessages) {
                    if (chatMessages == null || chatMessages.size() == 0) {
                        return;
                    }
                    for (ChatMessage chatMessage : chatMessages) {
                        if (chatMessage.is_mine) {
                            chatMessage.setItemType(2);
                            chatMessage.avatar = userInfo.getShowAvatar();
                        } else {
                            chatMessage.setItemType(1);
                            chatMessage.avatar = newsOwner.getShowAvatar();
                        }
                    }

                    recyclerAdapter.setDatas(chatMessages);

                    ChatMessage newChatMessage = chatMessages.get(chatMessages.size() - 1);
                    ChatSession chatSession = DbManager.getInstance().queryById(newChatMessage.is_mine ? newChatMessage.to_id : newChatMessage.mine_id, ChatSession.class);
                    if (chatSession != null) {
                        chatSession.msg = newChatMessage.msg;
                        DbManager.getInstance().save(chatSession);
                    }

//                    if (pageNumber == 1) {
//                        List<ChatMessage> chatMessageList = recyclerAdapter.getDatas();
//                        if (chatMessageList != null && chatMessageList.size() > 0) {
//                            chatMessages.addAll(chatMessageList);
//                        }
//                        recyclerAdapter.setDatas(chatMessages);
//                    } else {
//                        recyclerAdapter.addDatas(chatMessages);
//                    }
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    if (pageNumber == 1) {
                        onEndRefresh();
                    } else {
                        onEndLoadMore();
                    }
                    onFinishAsync();
                    isNoData();
                    RxBus.get().post(Constants.USERCHAT, Constants.USERCHAT);
                }
            });
        }

        public void sendMessage(String message) {
            if (newsOwner == null) {
                return;
            }
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setItemType(2);
            chatMessage.msg = message;
            chatMessage.create_time = System.currentTimeMillis() / 1000;
            chatMessage.status = 3;
            chatMessage.is_mine = true;
            chatMessage.mine_id = userInfo.uid;
            chatMessage.to_id = String.valueOf(newsOwner.uid);
            chatMessage.avatar = userInfo.getShowAvatar();

            recyclerAdapter.addData(recyclerAdapter.getDataCount(), chatMessage);
            recyclerAdapter.notifyDataSetChanged();

            chatSend((recyclerAdapter.getDataCount() - 1), message);
        }

        public void chatSend(int postion, String message) {
            HttpUtils.chatSend(newsOwner.uid, message, new HttpCallback<Object>(postion) {

                @Override
                public void onSuccess(Object o) {
                    int postion = (int) data;
                    ChatMessage chatMessage = recyclerAdapter.getItem(postion);
                    chatMessage.status = 1;
                    recyclerAdapter.notifyDataSetChanged();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                    int postion = (int) data;
                    ChatMessage chatMessage = recyclerAdapter.getItem(postion);
                    chatMessage.status = 4;
                    recyclerAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    isNoData();
                }
            });
        }

        public void isNoData() {
            if (mView != null) {
                if (recyclerAdapter.getDataCount() > 0) {
                    mView.setNoData(false);
                    commonRecycler.scrollToPosition(recyclerAdapter.getItemCount() - 1);
                } else {
                    mView.setNoData(true);
                }
            }
        }
    }

    class ChatAdapter extends BaseRecyclerMultiItemAdapter<ChatMessage> {

        private Activity mActivity;
        private View mView;

        public ChatAdapter(Activity activity, View view) {
            super(activity, null);
            this.mActivity = activity;
            this.mView = view;
            addItemType(1, R.layout.item_chat_message_from);
            addItemType(2, R.layout.item_chat_message_to);
        }

        @Override
        protected int getDefItemViewType(int position) {
            if (position >= getDataCount()) {
                return 0x00000333;
            }
            return super.getDefItemViewType(position);
        }

        @Override
        protected void setMultiData(ViewHolderHelper viewHolderHelper, int i, ChatMessage chatMessage) {
            if (i > 0) {
                long lastTime = getItem(i - 1).create_time;
                if (DateTimeUtils.isWithinOneMinute(chatMessage.create_time, lastTime)) {
                    viewHolderHelper.setVisibility(R.id.chat_timestamp, false);
                } else {
                    viewHolderHelper.setVisibility(R.id.chat_timestamp, true);
                    viewHolderHelper.setText(R.id.chat_timestamp, DateTimeUtils.getChatTime(chatMessage.create_time));
                }
            } else {
                viewHolderHelper.setVisibility(R.id.chat_timestamp, true);
                viewHolderHelper.setText(R.id.chat_timestamp, DateTimeUtils.getChatTime(chatMessage.create_time));
            }

            ImageView ivImg = viewHolderHelper.getView(R.id.chat_face);
            GlideUtils.getCircleImageToUrl(mActivity, chatMessage.avatar, ivImg, R.drawable.head_image);
            viewHolderHelper.setText(R.id.chat_text, chatMessage.msg);

            if (chatMessage.is_mine) {
                if (chatMessage.status > 2) {
                    switch (chatMessage.status) {
                        case 3:
                            viewHolderHelper.setVisibility(R.id.chat_sending, true);
                            viewHolderHelper.setVisibility(R.id.chat_state, false);
                            break;
                        case 4:
                            viewHolderHelper.setVisibility(R.id.chat_sending, false);
                            viewHolderHelper.setVisibility(R.id.chat_state, true);
                            viewHolderHelper.setItemChildClickListener(R.id.chat_state);
                            break;
                    }
                } else {
                    viewHolderHelper.setVisibility(R.id.chat_sending, false);
                    viewHolderHelper.setVisibility(R.id.chat_state, false);
                }
            }
        }
    }
}

